package com.ruoyi.common.utils.http;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * TODO
 *
 * @Author kingwin
 * @Date 2022/5/11 20:37
 */
public class HttpClients {


    public static String doPost(String url,String param){

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //参数实体
        StringEntity entity = new StringEntity(param,"UTF-8");

        //设置请求参数
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type","application/json; charset=utf-8");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;
        String content = null;

        try {
            //发送请求
            response = httpClient.execute(httpPost);
            //从响应体获取数据
            HttpEntity responseEntity = response.getEntity();
            System.out.println("HttpClient:Response:Status:" + response.getStatusLine());
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                content = EntityUtils.toString(responseEntity);
                System.out.println("ContentLength:" + responseEntity.getContentLength());
                System.out.println("Content:" + content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                return content;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return content;
    }
}
